package com.lc.settings

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ToastUtils
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit

class KeepAppUtil {

    companion object {
        private var dis: Disposable? = null

        val keepApp = "com.leessy.r229"

        var count = 0//连续3次检查服务未启动直接重启

        fun stop() {
            dis?.dispose()
        }

        fun startCheck(context: Context) {
            dis?.dispose()
            dis = Observable.interval(10, 10, TimeUnit.SECONDS).subscribe({
                checkStrat(context, keepApp)
            }, {
                it.printStackTrace()
                startCheck(context)
            })
        }

        private fun checkStrat(context: Context, pkg: String) {
            val appRunning = isAppRunning(context, pkg)
            Log.d("android", "os run - " + appRunning)
            if (!appRunning) {
                if (!TextUtils.isEmpty(pkg) && checkPackInfo(context, pkg)) {
                    count++
                    if (count > 3) {
//                        ToastUtils.showLong("设备检查异常，重启中。。。。")
                        Log.d("TAG", "checkStrat: count > 3 , 重启。。。")
                        DevicesBootUtil.reboot(context)
                        return
                    }
                    val serviceIntent = Intent()
                    serviceIntent.setPackage("com.leessy.r229")
                    serviceIntent.setClassName("com.leessy.r229", "com.leessy.r229.MService")
                    serviceIntent.putExtra("my_key", "App,hello~")
                    try {
                        context.startService(serviceIntent)
                    } catch (e: SecurityException) {
                        // 处理没有权限的情况
                        e.printStackTrace()
                    }
                }
            } else {
                count = 0
            }
        }

        /**
         * 检查包是否存在
         * @param packname
         * @return
         */
        private fun checkPackInfo(context: Context, packname: String): Boolean {
            var packageInfo: PackageInfo? = null
            try {
                packageInfo = context.packageManager.getPackageInfo(packname, 0)
            } catch (e: PackageManager.NameNotFoundException) {
//            e.printStackTrace();
            }
            return packageInfo != null
        }


        private fun isAppRunning(context: Context, packageName: String): Boolean {
            val activityManager =
                context.getSystemService(AppCompatActivity.ACTIVITY_SERVICE) as ActivityManager
            if (activityManager != null) {
                // 获取正在运行的应用进程
                for (processInfo in activityManager.runningAppProcesses) {
                    if (processInfo.processName == packageName) {
//                        val istop =
//                            processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        return true // 应用正在运行
                    }
                }
            }
            return false // 应用未在运行
        }
    }
}